package com.yf.course.modules.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.base.api.api.dto.PagingReqDTO;
import com.yf.course.modules.course.dto.CourseLearnDTO;
import com.yf.course.modules.course.dto.request.CourseLearnReqDTO;
import com.yf.course.modules.course.entity.CourseLearn;
import com.yf.course.modules.course.mapper.CourseLearnMapper;
import com.yf.course.modules.course.service.CourseFileLearnService;
import com.yf.course.modules.course.service.CourseFileService;
import com.yf.course.modules.course.service.CourseLearnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
* <p>
* 课程学习记录业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2020-12-17 11:28
*/
@Service
public class CourseLearnServiceImpl extends ServiceImpl<CourseLearnMapper, CourseLearn> implements CourseLearnService {


    @Override
    public IPage<CourseLearnDTO> paging(PagingReqDTO<CourseLearnReqDTO> reqDTO) {

        //转换结果
        IPage<CourseLearnDTO> pageData = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
        return pageData;
     }

    @Override
    public void reCheck(String courseId) {

        // 查找需要更新的数据
        List<CourseLearn> list = baseMapper.findForRefresh(courseId);
        if(CollectionUtils.isEmpty(list)){
            return;
        }

        for (CourseLearn item: list){
            // 状态同步
            if(item.getLearnFile() < item.getTotalFile()){
                item.setState(0);
            }else{
                item.setState(1);
            }
        }

        this.updateBatchById(list);

    }

    @Override
    public boolean finished(String courseId, String userId) {
        QueryWrapper<CourseLearn> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(CourseLearn::getCourseId, courseId)
                .eq(CourseLearn::getUserId, userId)
                .eq(CourseLearn::getState, 1);
        return this.count(wrapper) > 0;
    }
}
